using DA.AnimGraph;
using System;

namespace DA.AnimGraph.Editor {
    internal abstract class ContextPaneBase : NonContextPaneBase {

        internal AGEContext ageContext { get; private set; }
        protected override bool isValid { get => handleInternal != null; }

        AGAHandleBase handleInternal;
        protected AGAHandleBase handle {
            get => handleInternal;
            private set {
                OnSetHandle(value);
                handleInternal = value;
            }
        }

        protected ContextPaneBase(ContextPaneBase parent) : base(parent) {
            AGEGlobal.GetInstance().style.SS_Pane(this);
            ageContext = parent.ageContext;
        }

        protected ContextPaneBase(AGEEnvironment ageEnv) : base(ageEnv) {
            D.A(ageEnv.ageContext != null, "参数异常");
            ageContext = ageEnv.ageContext;
        }

        [Obsolete("不允许在 ContextPaneBase 及其子类中调用 Init 方法，使用 SetHandle 或 SetChildHandleFromParent 触发刷新", error: true)]
        public sealed override void Init() { }

        /// <summary>
        /// 触发 OnDrawUI，替代父类 Init
        /// </summary>
        internal void SetHandle(AGAHandleBase handle) {
            if (handle == this.handle) {
                return;
            }
            if (handle != null) {
                if (this.handle != null) {
                    OnClearUI();
                }
                this.handle = handle;
                OnDrawUI();
                // OnUpdateUI();
            } else {
                this.handle = null;
                OnClearUI();
            }
        }

        /// <summary>
        /// SetHandle 的替代方法，从父节点的 handle 中查找指定子 handle
        /// </summary>
        internal void SetHandleFromParent(AUID childUuid) {
            D.A(parentPane is ContextPaneBase, $"parentPane 必须是 ContextPaneBase, parentPane = {parentPane}, childUuid = {childUuid}");
            var p = parentPane as ContextPaneBase;
            var handle = p.handle.GetChildHandle(childUuid);
            if (handle == null) {
                D.E("OpenChild error, unknown uuid");
            }
            SetHandle(handle);
        }

        /// <summary>
        /// 目前用于各子类获取 HandleKeeper
        /// </summary>
        protected virtual void OnSetHandle(AGAHandleBase handle) { }
    }
}
